// 心跳队列防止微信回收
var HEART_TASK = null;
// var HEART_TASK_TIME = 30000;
var HEART_TASK_TIME = 5000;

// 加载
//  1 成功 2 失败 3 超时

// 数据初始化分段
var WEBSOCKET_LOOP_CACHE = [];
var WEBSOCKET_SECTION_TASK = [];
var WEBSOCKET_SECTION_TASK_INDEX = 0;
var WEBSOCKET_SECTION_TASK_MAX_LENGTH = 4000;

// 数据上传队列
var SECTION_TASK = null;
var SECTION_TASK_TIME = 1500;
// 是否在分段上传
var SECTION_TASK_FLAG = false;
// 分段上传完成后重复执行任务的间隔
// 循环上传
var SECTION_TASK_LOOP_TIME = 5000;

module.exports = {
	INIT_WEBSOCKET_CONNECT() {
		let _this = this;
		uni.connectSocket({
			url: _this.apiwss,
			success: res => {},
			fail: res => {},
		});
		// console.log(socketTask);
		uni.onSocketOpen(res => {
			_this.OPEN_SOCKET_HEART_TASK();
			_this.SOCKET_HEART_EVENT();
		});

		uni.onSocketMessage(res => {
			_this.LISTEN_SOCKET_MESSAGE(res);
		});

		uni.onSocketError(res => {
			console.log('WebSocket error');
		});

		uni.onSocketClose(res => {
			_this.CLOSE_SOCKET_HEART_TASK();
		});
	},
	OPEN_SOCKET_HEART_TASK() {
		let _this = this;
		_this.store_set_state({ state_name: 'WEBSOCKET_CONNECT', state_value: true });
		clearInterval(HEART_TASK);
		HEART_TASK = setInterval(() => {
			_this.SOCKET_HEART_EVENT();
		}, HEART_TASK_TIME);
	},
	SOCKET_HEART_EVENT() {
		let _this = this;
		let data = _this.BACK_SOCKET_TASK_DATA({}, 'ping');
		if (!SECTION_TASK_FLAG && _this.objJudge(data)) {
			_this.SEND_SOCKET_MESSAGE({ data });
		}
	},
	CLOSE_SOCKET_HEART_TASK() {
		let _this = this;
		_this.store_set_state({ state_name: 'WEBSOCKET_CONNECT', state_value: false });
		clearInterval(HEART_TASK);
		HEART_TASK = null;
	},
	SEND_SOCKET_MESSAGE(event) {
		let _this = this;
		let { data, success = res => {}, fail = res => {}, complete = res => {} } = event;
		if (!_this.WEBSOCKET_CONNECT) return;
		data = JSON.stringify(data);
		// console.log(data);
		uni.sendSocketMessage({ data, success, fail, complete });
	},
	INIT_WEBSOCKET_SECTION_TASK(event) {
		let _this = this;
		let { DATA, LOOP = false } = event;
		let FORM = DATA;
		WEBSOCKET_LOOP_CACHE = DATA;
		WEBSOCKET_SECTION_TASK = [];
		WEBSOCKET_SECTION_TASK_INDEX = 0;
		SECTION_TASK_FLAG = false;
		if (!_this.objJudge(FORM)) return;
		if (!_this.WEBSOCKET_CONNECT) return;
		let FORM_LENGTH = _this.GET_LENGTH(FORM);
		let PART = {};
		let P_i = 0;
		for (const k in FORM) {
			P_i++;
			PART[k] = FORM[k];
			let STR_LENGTH = JSON.stringify(PART).length;
			if (STR_LENGTH > WEBSOCKET_SECTION_TASK_MAX_LENGTH || P_i == FORM_LENGTH) {
				WEBSOCKET_SECTION_TASK.push(PART);
				PART = {};
			}
		}
		_this.START_WEBSOCKET_SECTION_TASK({ LOOP });
	},
	START_WEBSOCKET_SECTION_TASK(CONFIG) {
		let _this = this;
		let { LOOP } = CONFIG;
		let TASK = WEBSOCKET_SECTION_TASK[WEBSOCKET_SECTION_TASK_INDEX];
		TASK = _this.BACK_SOCKET_TASK_DATA(TASK);
		// console.log(TASK);
		if (!_this.objJudge(TASK)) return;
		_this.SEND_SOCKET_MESSAGE({
			data: TASK,
			success: res => {
				SECTION_TASK_FLAG = true;
			},
			fail: res => {
				console.log(res, TASK);
			},
			complete: res => {
				// 下一个任务的索引
				WEBSOCKET_SECTION_TASK_INDEX++;
				if (WEBSOCKET_SECTION_TASK_INDEX == WEBSOCKET_SECTION_TASK.length) {
					// 已经分段完成
					SECTION_TASK = null;
					SECTION_TASK_FLAG = false;
					// ----------- 发送结束指令给后端
					let data = _this.BACK_SOCKET_TASK_DATA({}, 'done');
					setTimeout(() => {
						_this.SEND_SOCKET_MESSAGE({ data });
					}, SECTION_TASK_TIME);
					// ----------- 发送结束指令给后端

					if (LOOP) {
						// 是否循环
						setTimeout(() => {
							_this.INIT_WEBSOCKET_SECTION_TASK({ DATA: WEBSOCKET_LOOP_CACHE, LOOP });
						}, SECTION_TASK_LOOP_TIME);
					}
				} else {
					// 分段写入
					clearTimeout(SECTION_TASK);
					SECTION_TASK = setTimeout(() => {
						_this.START_WEBSOCKET_SECTION_TASK(CONFIG);
					}, SECTION_TASK_TIME);
				}
			},
		});
	},

	BACK_SOCKET_TASK_DATA(msg = {}, type = 'client') {
		let _this = this;
		let time = _this.happenTimeFun(new Date().getTime(), 'y-m-d h:i:s');
		let token = uni.getStorageSync('usertoken');
		let { bluetooth_device_mac = false } = _this.BLUETOOTH_DEVICE_CONFIG;
		let DATA = {};
		if (bluetooth_device_mac) {
			DATA = {
				dev_id: bluetooth_device_mac, //设备编号
				type, //客户端发送用client   后台发送用admin
				msg,
				token, // 用户登录token,用于区分数据正确性
				time, // 当前时间
			};
		}
		return DATA;
	},

	LISTEN_SOCKET_MESSAGE(RES) {
		let _this = this;
		let DATA = JSON.parse(RES.data);
		_this.GET_SOCKET_MESSAGE_TYPE(DATA);
	},
	// 指令统一中转匹配不同方法
	GET_SOCKET_MESSAGE_TYPE(DATA) {
		let _this = this;
		console.log(DATA);
		// let { dev_id, msg, type } = { dev_id: 'A5:C2:37:00:2D:3C', type: 'edit', msg: { form_key: 'refresh', value: '1' }, token: 'AABBCC', time: new Date() };
		let { dev_id = false, msg = {}, type = false } = DATA;

		// if (dev_id == _this.BLUETOOTH_DEVICE_CONFIG.bluetooth_device_mac) {

		// }
		// console.log(msg);
		if (_this.gettype(msg) == 'String') {
			msg = JSON.parse(msg);
		}
		let { key, value } = msg;

		switch (type) {
			case 'admin':
				if (key == 'refresh' && value == 1) {
					setTimeout(() => {
						_this.INIT_WEBSOCKET_SECTION_TASK({ DATA: _this.BLUETOOTH_INIT_FORM, LOOP: false });
					}, SECTION_TASK_TIME);
				}
				break;
			case 'cmd':
				// console.log(DATA);
				_this.store_set_state({ state_name: 'WEBSOCKET_COMMADN_EDIT', state_value: true });
				_this.HANDLE_SOCKET_TO_EDIT_BLUETOOTH(msg);
				break;
		}
	},
};
